from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
import random

from meiduo.meiduo.utils.exceptions import logger
from meiduo.meiduo.libs.yuntongxun.sms import CCP
from . import constants


# Create your views here.


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):

        # 创建redis连接对象
        redis_conn = get_redis_connection("verify_code")
        # 创建管道
        pl = redis_conn.pipeline()
        # 创建一个标记  60秒能不能重复发送短信
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({"message": "发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)
        sms_code = "%06d" % random.randint(0, 999999)
        logger.debug(sms_code)
        CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], constants.SEND_SMS_TEMPLATE_ID)
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.sexex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        return Response({"message": "OK"})
